%2D gaussian fit
function[error] = gaussianoffset(fitpar,params,Xdata,Ydata,img)
A = fitpar(1);
xc = fitpar(2);
yc = fitpar(3);
wx = fitpar(4);
wy = fitpar(5);
% A2 = fitpar(6);
% wx2 = fitpar(7);
% wy2 = fitpar(8);
offset = params;


[d1,d2] = size(img);

X = Xdata;
Y = Ydata;
xmax=max(max(X));
xmin=min(min(X));
ymax=max(max(Y));
ymin=min(min(Y));

if xc>xmax||xc<xmin 
    xc=(xmax+xmin)/2;
end
if yc>ymax||yc<ymin 
    yc=(ymax+ymin)/2;
end

area1 = (X-xc).^2./(2.*wx.^2)+(Y-yc).^2./(2.*wy.^2);
% area2 = (X-xc).^2./(2*wx2.^2)+(Y-yc).^2./(2*wy2.^2);
gaussian2D = offset + A.*exp(-area1);% + A2.*exp(-area2);
errM = (img - gaussian2D).^2;
error = sum(sum(errM))./(d1*d2);

end
